##
## Email.py 
##
## Creates and sends emails to users and listserv.
##
##
## Author: Shannon Eric Peevey <speeves@erikin.com>, 2 April 2004
##

import smtplib
from email.MIMEText import MIMEText
import re

class EmailFunc:
    """This class offers email  functionality to the
	cwsAdmin.py script"""

    def RunEmail(self, config, utilityObject):
        # this will interact with the user to generate emails
        # for the end-user
        print """
        Now, we will need to generate the emails that will be
        sent to the new user(s)...\n
        """

        print "First, we will need some information about the user...\n"

        firstName = raw_input("First Name? ")
        lastName = raw_input("Last Name? ")
        emailAddress = raw_input("Email Address? ")
        webUrl = raw_input("This email regards which URL? ")
        dbName = raw_input("Database? ")
        dbUser = raw_input("Limited DB User? ")
        dbPasswd = raw_input("Limited DB Password? ")

        print "\nNow, we will need to know which services they are going to use...\n"

        print "These are the services that are available at this time:\n"

        for service in config['Email']['Server' + config['Session']['Email']['CurrentServer']]["availableServices"]:
            index = config['Email']['Server' + config['Session']['Email']['CurrentServer']]["availableServices"].index(service) + 1
            print "(" + str(index) + ") " + service

        serviceList = raw_input("Please, enter the numbers of the services here: (ie. 2 5 3) ")

        emailSkelDir = config['Email']['Server' + config['Session']['Email']['CurrentServer']]["emailSkelDir"]
        finalBodyList = []

        # add the URL of the web that this email pertains to
        webUrlText = "Re: New Web: " + webUrl
        dbInfoText = "\n\n(For PHP developers) \nNew Database: " + dbName  + "  \nLimited Database User: " + dbUser  + "  \nLimited Database User Password: " + dbPasswd  + "  \nDatabase Host: " + config['Mysql']['Server' + config['Session']['Mysql']['CurrentServer']]["mysqlHostname"] + "\n\n"
        finalBodyList.append(webUrlText)
        finalBodyList.append(dbInfoText)
        
        # grab the salutation and make the changes necessary
        salutation = utilityObject.GrabTextList(emailSkelDir + 'salutation.skel')
        finalBodyList.append(salutation)
        
        serviceArray = re.split(' ', serviceList)
        # Begin building the body of email
        for service in serviceArray:
            serviceName = ''
            for name in availableServices:
                serviceIndex = availableServices.index(name) + 1
                ## DEBUGGING
                if config['General']["debugLevel"] == '5':
                    print "service == ", service
                    print "name == ", name
                    print "serviceIndex == ", serviceIndex
                    
                if str(serviceIndex) == str(service):
                    ## DEBUGGING
                    if config['General']["debugLevel"] == '5':
                        print "str(serviceIndex) is equal str(service)"
                    serviceName = name
            # split array and put the message together
            bodyText = utilityObject.GrabTextList(emailSkelDir + serviceName + ".skel")
            finalBodyList.append(bodyText)
            bodyText = ""

        # Add the signature to the end of the email
        signature = utilityObject.GrabTextList(emailSkelDir + 'signature.skel')
        finalBodyList.append(signature)

        ## DEBUGGING
        if config['General']["debugLevel"] == '5':
            print "finalBodyList == ", finalBodyList

        finalBodyText = ""
        for listMember in finalBodyList:
            ## DEBUGGING
            if config['General']["debugLevel"] == '5':
                print "listMember == ", listMember
            for member in listMember:
                ## DEBUGGING
                if config['General']["debugLevel"] == '5':
                    print "member == ", member
                    
                finalBodyText = finalBodyText + member

        # DEBUGGING
        if config['General']["debugLevel"] == '5':
            print "finalBodyText == ", finalBodyText
        # Join the finalBody array into a text body for the email.

        #for item in finalBodyText:
        #    print "item == ", item
        #finalBodyText = "\n".join(finalBodyList)

        # send the emails
        self.SendEmail(config, emailAddress, finalBodyText)

        addToList = raw_input("Do you want to add this user to a listserv? ([y]/n) ")
        if addToList == "":
            addToList = "y"

        if addToList == "y":
            # set addRemove to a => add user
            self.AddListUser( config, availableListServs, emailAddress, firstName, lastName)
            
    def AddListUser(self, config, availableListServs, emailAddress="", firstName="", lastName=""):
        # function to get information to add users to lists
        if firstName == "":
            firstName = raw_input("First Name? ")
        if lastName == "":
            lastName = raw_input("Last Name? ")
        if emailAddress == "":
            emailAddress = raw_input("Email Address? ")

        print "\nNow, we need to Add them to the appropriate listservs\n"

        print "These are the available lists:\n"

        for list in availableListServs:
            index = availableListServs.index(list) + 1
            print "(" + str(index) + ") " + list

        listList = raw_input("Enter Lists Here: (ie 1 3 5) ")

        listArray = re.split(' ', listList)

        for list in listArray:
            # add the users to the list
            listText = availableListServs[int(list) - 1]

            # Generate email text and send to listserv for subscribing user
            finalText = self.AnnounceListAddUser(listText, emailAddress, firstName, lastName)

            # send the email
            self.SendEmail( config, finalText)
            
        print """
        \nThe listserv will respond to the admin user, and that user must
        respond, before the users are finally added to the lists...
        """

    def RemoveListUser(self,  config, availableListServs, emailAddress=""):
        # function to get information to add users to lists
        if emailAddress == "":
            emailAddress = raw_input("Email Address? ")

        print "\nNow, we need to Remove them from the appropriate listservs\n"

        print "These are the available lists:\n"

        for list in availableListServs:
            index = availableListServs.index(list) + 1
            print "(" + str(index) + ") " + list

        listList = raw_input("Enter Lists Here: (ie 1 3 5) ")

        listArray = re.split(' ', listList)

        for list in listArray:
            # add the users to the list
            listText = availableListServs[int(list) - 1]

            finalText = self.AnnounceListDeleteUser(listText, emailAddress)

            # send the email
            self.SendEmail(config, finalText)
            
        print """
        \nThe listserv will respond to the admin user, and that user must
        respond, before the users are finally added to the lists...
        """

    def AnnounceListAddUser(self, list, emailAddress, firstName, lastName):
        #this generates the text for the listserv
        listServ = "add " + list + " " + emailAddress + " " + firstName + " " + lastName

        return listServ

    def AnnounceListDeleteUser(self, list, emailAddress):
        #this generates the text for the listserv
        listServ = "delete " + list + " " + emailAddress

        return listServ


    def SendEmail(self, config, emailAddress, bodyText):

        msg = MIMEText(bodyText)
        # me == the sender's email address
        # you == the recipient's email address
        msg['Subject'] = config['Email']['Server' + config['Session']['Email']['CurrentServer']]["welcomeEmailSubject"]
        msg['Bcc'] = config['General']["adminEmail"]
        msg['From'] = config['General']["adminEmail"]
        msg['To'] = emailAddress

        # Send the message via our own SMTP server, but don't include the
        # envelope header.
        s = smtplib.SMTP()
        s.connect()
        s.sendmail(config['General']["adminEmail"], emailAddress, msg.as_string())
        s.close()
